<template>
  <div class="search">
    <Card>
      <Row class="operation">
        <Button @click="add" type="primary" icon="md-add" v-show="showType==='tree'">添加子菜单</Button>
        <Button @click="addRoot" icon="md-add">添加目录</Button>
        <Button @click="deleteAll" icon="md-trash">批量删除</Button>
        <Button @click="refresh" :loading="refreshFlag" icon="md-refresh">刷新</Button>
        <Input
          v-model="searchText"
          suffix="ios-search"
          @on-change="onSearch"
          placeholder="输入菜单名称搜索"
          clearable
          style="width: 250px"
          v-show="showType==='list'"
        />
        <i-switch v-model="strict" size="large" v-show="showType==='tree'" style="margin-left:5px">
          <span slot="open">级联</span>
          <span slot="close">单选</span>
        </i-switch>
        <div style="float: right">
          <RadioGroup v-model="showType" type="button">
            <Radio title="树结构" label="tree">
              <Icon type="md-list"></Icon>
            </Radio>
            <Radio title="列表" label="list">
              <Icon type="ios-apps"></Icon>
            </Radio>
          </RadioGroup>
        </div>
      </Row>
      <Row type="flex" justify="start" v-show="showType==='tree'">
        <Col :md="8" :lg="8" :xl="6">
          <Row>
            <Alert show-icon>
              当前选择编辑：
              <span class="select-title">{{editTitle}}</span>
              <a class="select-clear" v-if="form.menuId" @click="cancelEdit">取消选择</a>
            </Alert>
            <Input
              v-model="searchText"
              suffix="ios-search"
              @on-change="onSearch"
              @on-clear="clearTreeData"
              placeholder="输入菜单名称搜索"
              clearable
            />
            <div class="tree-bar" :style="{maxHeight: maxHeight}">
              <Tree
                ref="tree"
                :data="data"
                show-checkbox
                @on-check-change="changeSelect"
                @on-select-change="selectTree"
                :check-strictly="!strict"
              ></Tree>
              <Spin size="large" fix v-if="loading"></Spin>
            </div>
          </Row>
        </Col>
        <Col :md="15" :lg="13" :xl="9" style="margin-left: 10px;">
          <Form ref="form" :model="form" :label-width="100" :rules="rules">
            <FormItem label="类型" prop="type">
              <div v-show="form.type===0">
                <Icon type="ios-navigate-outline" size="16" style="margin-right:5px;"></Icon>
                <span>目录</span>
              </div>
              <div v-show="form.type===1">
                <Icon type="ios-list-box-outline" size="16" style="margin-right:5px;"></Icon>
                <span>页面菜单</span>
              </div>
              <div v-show="form.type===2">
                <Icon type="md-radio-button-on" size="16" style="margin-right:5px;"></Icon>
                <span>操作按钮</span>
              </div>
            </FormItem>
            <FormItem label="菜单名称" prop="name">
              <Input v-model="form.name" placeholder="输入菜单名称"/>
            </FormItem>
            <FormItem label="菜单路径" prop="path" v-if="form.type===0||form.type===1">
              <Input v-model="form.path" placeholder="输入菜单路径"/>
            </FormItem>
            <FormItem label="前端组件" prop="component" v-if="form.type===0||form.type===1">
              <Input v-model="form.component" placeholder="输入前端组件"/>
            </FormItem>
            <FormItem label="默认跳转地址" prop="redirect" v-if="form.type===0||form.type===1">
              <Input v-model="form.redirect" placeholder="输入默认跳转地址"/>
            </FormItem>
            <FormItem label="操作权限" prop="perms" v-if="form.type===1||form.type===2">
              <Input v-model="form.perms" placeholder="输入操作权限"/>
            </FormItem>
            <FormItem label="聚合路由" prop="alwaysShow" v-if="form.type===0||form.type===1">
              <i-switch size="large" v-model="form.alwaysShow" :true-value="true" :false-value="false">
                <span slot="open">是</span>
                <span slot="close">否</span>
              </i-switch>
            </FormItem>
            <FormItem label="图标" prop="icon" v-if="form.type===0||form.type===1">
              <icon-choose v-model="form.icon"></icon-choose>
            </FormItem>
            <FormItem label="备注" prop="remark">
              <Input v-model="form.remark" type="textarea" :rows="5"/>
            </FormItem>
            <Form-item class="br">
              <Button
                @click="submitEdit"
                :loading="submitLoading"
                type="primary"
                icon="ios-create-outline"
              >修改并保存</Button>
              <Button @click="handleReset">重置</Button>
            </Form-item>
          </Form>
        </Col>
      </Row>
      <Alert show-icon v-if="showType==='list'">
        已选择
        <span class="select-count">{{selectCount}}</span> 项
        <a class="select-clear" @click="clearSelectAll">清空</a>
      </Alert>
      <Table
        :loading="loading"
        row-key="name"
        border
        :columns="columns"
        :data="data"
        sortable="custom"
        @on-selection-change="showSelect"
        ref="table"
        v-if="showType==='list'"
      ></Table>
    </Card>
    <Modal
      v-model="modalVisible"
      :mask-closable="false"
      width="550px"
      :title="formAddTitle">
      <Form ref="formAdd" :model="formAdd" :label-width="120" :rules="addFormRules">
        <div v-if="showParent">
          <FormItem label="上级菜单："><Tag color="green">{{parentTitle}}</Tag></FormItem>
        </div>
        <FormItem label="类型">
          <div v-show="formAdd.type===0">
            <Icon type="ios-navigate-outline" size="16" style="margin-right:5px;"></Icon>
            <span>目录</span>
          </div>
          <div v-show="formAdd.type===1">
            <Icon type="ios-list-box-outline" size="16" style="margin-right:5px;"></Icon>
            <span>页面菜单</span>
          </div>
          <div v-show="formAdd.type===2">
            <Icon type="md-radio-button-on" size="16" style="margin-right:5px;"></Icon>
            <span>操作按钮</span>
          </div>
        </FormItem>
        <FormItem label="菜单名称" prop="name">
          <Input v-model="formAdd.name" placeholder="输入菜单名称"/>
        </FormItem>
        <FormItem label="菜单路径" prop="path" v-if="formAdd.level===1||formAdd.level===2">
          <Input v-model="formAdd.path" placeholder="输入菜单路径"/>
        </FormItem>
        <FormItem label="前端组件" prop="component" v-if="formAdd.level===1||formAdd.level===2">
          <Input v-model="formAdd.component" placeholder="输入前端组件"/>
        </FormItem>
        <FormItem label="默认跳转地址" prop="redirect" v-if="formAdd.level===1||formAdd.level===2">
          <Input v-model="formAdd.redirect" placeholder="输入默认跳转地址"/>
        </FormItem>
        <FormItem label="操作权限" prop="perms" v-if="formAdd.level===2||formAdd.level===3">
          <Input v-model="formAdd.perms" placeholder="输入操作权限"/>
        </FormItem>
        <FormItem label="聚合路由" prop="alwaysShow" v-if="formAdd.level===1||formAdd.level===2">
          <i-switch size="large" v-model="formAdd.alwaysShow" :true-value="true" :false-value="false">
            <span slot="open">是</span>
            <span slot="close">否</span>
          </i-switch>
        </FormItem>
        <FormItem label="图标" prop="icon" v-if="formAdd.level===1||formAdd.level===2">
          <icon-choose v-model="formAdd.icon"></icon-choose>
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input v-model="formAdd.remark" type="textarea" :rows="5"/>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="cancelAdd">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submitAdd">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {getMenuList,saveMenu,updateMenu,deleteMenu,searchMenu} from "@/api/menu";
import IconChoose from "@/components/icons/icon-choose"
export default {
  name: "Menu",
  components:{
    IconChoose
  },
  data(){
    return{
      maxHeight:'500px',
      strict:false,
      showType:'tree',
      refreshFlag:false,
      searchText:'',
      loading:false,
      searchDeptTitle:'',
      editData:[],
      editTitle:'',
      formAdd:{},
      selectCount:0,
      selectList:[],
      formAddTitle:'',
      data:[],
      showParent:false,
      parentTitle:'',
      modalVisible:false,
      submitLoading:false,
      form:{
        alwaysShow:1,
        type:1,
        menuId:'',
        title:'',
        name:'',
        parentId:'',
        perms:'',
        path:'',
        component:'',
        icon:'',
        sort:null,
        redirect:'',
        isFrame:'',
      },
      addFormRules:{
        name:[
          {required:true,message:'请输入菜单名称',trigger:'blur'}
        ],
        path:[
          {required:true,message:'请输入菜单路径',trigger:'blur'}
        ],
        component:[
          {required:true,message:'请输入前端组件',trigger:'blur'}
        ],
        perms:[
          {required:true,message:'请输入权限标识',trigger:'blur'}
        ],
        icon:[
          {required:true,message:'请选择图标',trigger:'change'}
        ],
      },
      rules:{
        name:[
          {required:true,message:'请输入操作权限',trigger:'blur'}
        ],
        path:[
          {required:true,message:'请输入菜单路径',trigger:'blur'}
        ],
        component:[
          {required:true,message:'请输入前端组件',trigger:'blur'}
        ],
        perms:[
          {required:true,message:'请输入权限标识',trigger:'blur'}
        ],
        icon:[
          {required:true,message:'请选择图标',trigger:'change'}
        ]
      },
      columns:[
        {
          type: "selection",
          width: 60,
          align: "center",
          fixed: "left"
        },
        {
          type: "index",
          width: 60,
          align: "center",
          fixed: "left"
        },
        {
          title: "菜单名称",
          key: "name",
          minWidth: 120,
          sortable: true,
          tree: true
        },
        {
          title: "父级菜单",
          key: "parentName",
          minWidth: 120,
          sortable: true,
          align: "center",
        },
        {
          title: "跳转地址",
          key: "path",
          minWidth: 120,
          sortable: true,
          align: "center",
          render:(h,params)=>{
            return h('div',[
              h(
                "Tag",
                {
                  style: {
                    marginRight: "5px"
                  },
                  props:{
                    color:(params.row.component!=null&&params.row.component!='')?'success':'warning',
                  }
                },
                (params.row.path!=null&&params.row.path!='')?params.row.path:'操作按钮'
              ),
            ])
          }
        },
        {
          title: "前端组件",
          key: "component",
          minWidth: 120,
          sortable: true,
          align: "center",
          render:(h,params)=>{
            return h('div',[
              h(
                "Tag",
                {
                  style: {
                    marginRight: "5px"
                  },
                  props:{
                    color:(params.row.component!=null&&params.row.component!='')?'success':'warning',
                  }
                },
                (params.row.component!=null&&params.row.component!='')?params.row.path:'操作按钮'
              ),
            ])
          }
        },
        {
          title: "图标",
          key: "icon",
          width: 150,
          sortable: true,
          align: "center",
          sortType: "asc",
          render:(h,params)=>{
            if(params.row.component!=null&&params.row.component!=''){
              return ('div',[
                h('Icon',
                  {
                    props:{
                      type:params.row.icon
                    }
                  },
                  (params.row.component==null||params.row.component=='')?'按钮无图标':'按钮无图标'
                )
              ])
            }else{
              return ('div',[
                h('Strong',
                  '按钮无图标'
                )
              ])
            }
          }
        },
        {
          title: "创建时间",
          key: "createTime",
          sortable: true,
          width: 200
        },
        {
          title: "操作",
          key: "action",
          width: 300,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.tableAdd(params.row);
                    }
                  }
                },
                " 添加子菜单"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.del(params.row);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
    }
  },
  methods:{
    add(){
      if (!this.form.menuId) {
        this.$Message.warning("请先点击选择一个菜单权限节点");
        return;
      }
      debugger
      this.formAddTitle = '添加菜单';
      this.showParent=true;
      this.parentTitle = this.form.title;
      let type = 0;
      if (this.form.level === 1) {
        type = 1;
      } else if (this.form.level === 2) {
        type = 2;
      } else if (this.form.level === 3) {
        this.$Modal.warning({
          title: "抱歉，不能添加啦",
          content: "仅支持2级菜单目录"
        });
        return;
      } else {
        type = 0;
      }
      if (this.form.level === 1) {
        this.formAdd.path = "/";
        this.formAdd.component = "Main";
      }
      this.formAdd = {
        icon: "",
        type: type,
        parentId: this.form.menuId,
        level: Number(this.form.level) + 1,
        sort: 0,
        showAlways: true
      };
      this.modalVisible = true;
    },
    tableAdd(row){
      this.formAddTitle = '添加菜单';
      this.showParent=true;
      this.parentTitle =row.parentName;
      let type = 0;
      if (row.level === 1) {
        type = 1;
      } else if (row.level === 2) {
        type = 2;
      } else if (row.level === 3) {
        this.$Modal.warning({
          title: "抱歉，不能添加啦",
          content: "仅支持2级菜单目录"
        });
        return;
      } else {
        type = 0;
      }
      if (row.level === 1) {
        this.formAdd.path = "/";
        this.formAdd.component = "Main";
      }
      this.formAdd = {
        icon: "",
        type: type,
        parentId: row.menuId,
        level: Number(row.level) + 1,
        sort: 0,
        showAlways: true
      };
      this.modalVisible = true;
    },
    addRoot(){
      this.formAddTitle = "添加一级菜单";
      this.showParent = false;
      this.formAdd = {
        type: 0,
        level: 1,
        parentId: 0,
        sort: 0,
        component:"Main"
      };
      this.modalVisible = true;
    },
    del(row){
      this.selectCount=1;
      this.selectList.push(row);
      this.deleteAll();
    },
    deleteAll(){
      if(this.selectList.length<=0){
        this.$Message.warning("请选择要删除的数据");
        return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content:"您确认要删除所选的 " + this.selectCount + " 条数据及其下级所有数据?",
        loading: true,
        onOk: () => {
          let data=this.selectList;
          let ids='';
          data.forEach(e=>{
            ids+=e.menuId+','
          })
          ids=ids.substring(0,ids.length-1);
          deleteMenu(ids).then(res=>{
            if(res.code===200){
              this.$Message.success('操作成功');
            }
            this.selectList = [];
            this.selectCount = 0;
            this.$Modal.remove()
            this.cancelEdit();
            this.init();
          })
        }
      });
    },
    refresh(){
      let that=this;
      that.refreshFlag=true;
      that.init();
      setTimeout(function (){
        that.refreshFlag=false;
      },1000)
    },
    onSearch(){
      if(this.searchText){
        this.loading=true
         searchMenu({searchText:this.searchText}).then(res=>{
           if(res.code===200){
              this.data=res.data;
              this.loading=false;
           }
         })
      }
    },
    showSelect(v){
      this.selectCount=v.length;
      this.selectList=v;
    },
    clearTreeData(){
      this.searchText='';
      this.init();
    },
    cancelAdd(){
      this.modalVisible=false;
      this.$refs['formAdd'].resetFields();
    },
    submitAdd(){
      this.$refs['formAdd'].validate((valid)=>{
        if(valid){
          this.submitLoading=true;
          this.formAdd.title=this.formAdd.name;
          saveMenu(this.formAdd).then(res=>{
            if(res.code===200){
               this.$Message.success('添加成功');
               this.modalVisible=false;
               this.submitLoading=false;
               this.$refs.formAdd.resetFields();
               this.init();
            }
          }).catch((error)=>{
            this.submitLoading=false;
          })
        }
      })
    },
    clearSelectAll(){

    },
    submitEdit(){
      if (!this.form.menuId) {
        this.$Message.warning("请先选择要修改的菜单");
        return;
      }
      this.$refs['form'].validate((valid)=>{
        if(valid){
          this.submitLoading=true;
          delete this.form.children;
          delete this.form.createTime
          this.form.title=this.form.name;
          updateMenu(this.form).then(res=>{
            if(res.code===200){
               this.$Message.success("修改成功");
               this.submitLoading=false;
               this.init();
            }
          }).catch((error)=>{
            this.submitLoading=false;
          })
        }
      })
    },
    handleReset(){
      this.submitLoading=false;
      this.$refs.form.resetFields();
    },
    changeSelect(v){
      this.selectList=v;
      this.selectCount=v.length;
    },
    selectTree(v){
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        this.editTitle = data.title;
        this.form = data;
      } else {
        this.cancelEdit();
      }
    },
    selectEditTree(){

    },
    clearEditData(){

    },
    selectTreeEdit(){

    },
    cancelEdit(){
      let data = this.$refs.tree.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.$refs.form.resetFields();
      delete this.form.menuId;
      this.editTitle = "";
    },
    queryMenuData(){
      getMenuList().then(res=>{
        if(res.code===200){
           this.data=res.data;
        }
      })
    },
    init(){
      this.queryMenuData();
    }
  },
  mounted(){
    let height = document.documentElement.clientHeight;
    this.maxHeight = Number(height - 287) + "px";
    this.init();
  }
}
</script>

<style lang="less">
@import "../../styles/tree-common.less";
</style>
